<?php
class Post extends Controller {
	function Post(){
		parent::Controller();	
	}
	
	function submit(){
		
		$inputField = stripslashes($this->input->post('inputField'));
		$inputField = mysql_real_escape_string(strip_tags($inputField));
		if(mb_strlen($this->input->post('inputField')) < 1 || mb_strlen($this->input->post('inputField'))>140)
		die("0");
		$date = time();
		$att['isImg'] = $this->input->post('isimg');
		$att['imgName'] = $this->input->post('imgname');
		$att['isFile'] = $this->input->post('isfile');
		$att['fileName'] = $this->input->post('filename');
		echo $this->_formatTweet($inputField,$date,$att);
		
	}
	
	function _formatTweet($tweet,$dt,$att){
		$this->load->model('UsersDetail');
		$this->load->model('UserMahasiswa');
		$this->load->model('User');
		$this->load->model('Notif');
		$this->load->model('Posts');
		$this->load->model('Groupsdb');
		$this->load->model('Attachment');
		
		$detail = json_decode($this->UsersDetail->getDetail($this->session->userdata('userId')));
		$avatar = $detail->avatar;
		$username = $this->User->getUsername($this->session->userdata('userId'));
		$nama = json_decode($this->UserMahasiswa->getNama($this->session->userdata('userId')))->nama;

		$tweet=htmlspecialchars(stripslashes($tweet));
		
		//tag user
		preg_match_all("/@(\w+)/",$tweet,$mentions, PREG_OFFSET_CAPTURE);

		$takenUsername = $this->User->usernameIsUsed();
			
		$allGroup=$this->Groupsdb->getAllGroups();
		$mentioned = array();
		$mentionedGroup = array();
		for($i=0;$i<sizeOf($mentions[1]);$i++){
			if(!in_array($mentions[1][$i][0],$takenUsername)||$mentions[1][$i][0]==$username){
				if($allGroup){
					if(!in_array($mentions[1][$i][0],$allGroup['groupname'])){
						$tweet = str_replace("@".$mentions[1][$i][0]."",$mentions[1][$i][0],$tweet);
					}else{
						$tweet = str_replace("@".$mentions[1][$i][0]."","@%".$mentions[1][$i][0],$tweet);
						$mentionedGroup[] = $mentions[1][$i][0];
					}
				}else{
					$tweet = str_replace("@".$mentions[1][$i][0]."",$mentions[1][$i][0],$tweet);
				}
			}else{
				$mentioned[] = $mentions[1][$i][0];
			}
			
		}
		
		//tag kata
		$tagged = array();
		preg_match_all("/#(\w+)/",$tweet,$tags, PREG_OFFSET_CAPTURE);
		for($i=0;$i<sizeOf($tags[1]);$i++){
			$tagged[] = $tags[1][$i][0];
		}
		
		$attach = 0;
		if($att['isImg']==1||$att['isFile']==1){
			$attach = 1;
		}
		
		//saving
		if($insertPost = $this->Posts->insertPost($this->session->userdata('userId'),
			    					NULL,
			    					$tweetit=str_replace("'","\'",$tweet),
			    					(sizeOf($mentioned)+sizeOf($mentionedGroup)),
			    					$attach,
			    					sizeOf($tagged),
			    					$comments=NULL,
			    					$dt,
			    					$date_lastcomment=NULL)){
			if(sizeOf($mentioned)>0){
				for($i=0;$i<sizeOf($mentioned);$i++){
					$this->Posts->insertMentioned($insertPost,$this->UsersDetail->getUserIdFromUsername($mentioned[$i]));
					$this->Notif->insertNotifMentioned($insertPost,$this->UsersDetail->getUserIdFromUsername($mentioned[$i]),$this->session->userdata('userId'));
				}
			}
			if(sizeOf($tagged)>0){
				for($i=0;$i<sizeOf($tagged);$i++){
					$this->Posts->insertTagged($insertPost,$tagged[$i]);
				}
			}if(sizeOf($mentionedGroup)>0){
				for($i=0;$i<sizeOf($mentionedGroup);$i++){
					$group = $this->Groupsdb->getGroup($mentionedGroup[$i]);
					$this->Posts->insertMentionedGroup($insertPost,$group['id']);
					$membersGroup = $this->Groupsdb->getMembersGroup($group['id']);
					for($j=0;$j<sizeOf($membersGroup['id']);$j++){
						if($membersGroup['id'][$j]!=$this->session->userdata('userId')){
							$this->Notif->insertNotifMentioned($insertPost,$membersGroup['id'][$j],$this->session->userdata('userId'));
						}
					}
				}
			}
			$attachedHTML='<ul id="listAttach">';
			if($att['isImg']==1){
				$this->Attachment->insertAttachment($insertPost,'image',$att['imgName']);
				$attachedHTML = $attachedHTML.'<li>
				<a href="'.base_url().'sknimg/i-see-attr/imageAttachment/'.$att['imgName'].'" class="lightbox-enabled" onclick="$(this).lightbox({start:true,events:false}); return false;" title="'.$att['imgName'].'">
					<img class="avatarecho" style="float:right;" src="'.base_url().'sknimg/i-see-attr/imageAttachmentThumb/'.$att['imgName'].'" width="50px" height="50px"  />
				</a>
				<br><strong style="font-size:11px;font-style:italic;">
				<img src="'.base_url().'sknimg/img/download.png" width="15" height="15"></img>
				<a href="'.base_url().'engine/download/item/'.$att['imgName'].'/image">
				Image Attachment: '.$att['imgName'].'</a>
				</strong>
				<div class="tweetTxt">
				';
				$attachedHTML = $attachedHTML.'</div> <div class="clear"></div> </li>';
			}
			if($att['isFile']==1){
				$this->Attachment->insertAttachment($insertPost,'file',$att['fileName']);
				$attachedHTML = $attachedHTML.'<li>
				<a href="javascript:;"><img class="avatarecho" style="float:right;border:0" src="'.base_url().'sknimg/img/'.'file.png'.'" width="40px" height="45px"  /></a>
				<br><strong style="font-size:11px;font-style:italic;">
				<img src="'.base_url().'sknimg/img/download.png" width="15" height="15"></img>
				<a href="'.base_url().'engine/download/item/'.$att['fileName'].'/file">
				File Attachment: '.$att['fileName'].'</a></strong>
				<div class="tweetTxt">
				';
				$attachedHTML = $attachedHTML.'</div> <div class="clear"></div> </li>';
			}
			$attachedHTML=$attachedHTML."</ul>";
		
		
			//formatting
			$tweet = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" rel=\"nofollow\">\\2</a>", $tweet);
			$tweet = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" rel=\"nofollow\">\\2</a>", $tweet);
	  		$tweet = preg_replace("/@(\w+)/", "<a href=\"".base_url()."profile/info/"."\\1\" rel=\"nofollow\">@\\1</a>", $tweet);
	  		$tweet = preg_replace("/@%(\w+)/", "<a href=\"".base_url()."groups/info/"."\\1\" rel=\"nofollow\">@\\1</a>", $tweet);
	  		$tweet = preg_replace("/#(\w+)/", '<a href="'.base_url().'search/tag/'.'\\1" rel=\"nofollow\">#\\1</a>', $tweet);
			if($avatar==''){
				$avatar = 'default_avatar.jpg';
			}
			return'
			<li><a href="'.base_url().'profile/info/'.$username.'"><img class="avatarecho" src="'.base_url().'sknimg/i-see-attr/avatarThumb/'.$avatar.'" width="50px" height="50px" alt="avatar" /></a>
			<div class="tweetTxt">
			<strong><a href="'.base_url().'profile/info/'.$username.'">'.$nama.'</a></strong> '. $tweet.